package ${domain}.action.ajax.wsys;

import org.springframework.beans.factory.annotation.Autowired;
import ${domain}.frame.base.ErrorType;
import ${domain}.frame.schedule.Scheduler;
import ${domain}.frame.utils.StringUtil;
import ${domain}.module.wsys.req.ScheduleFindRequest;
import ${domain}.module.wsys.req.ScheduleStartRequest;
import ${domain}.module.wsys.req.ScheduleStopRequest;
import ${domain}.module.wsys.rsp.ScheduleFindResponse;
import ${domain}.module.wsys.rsp.ScheduleStartResponse;
import ${domain}.module.wsys.rsp.ScheduleStopResponse;

import java.util.Iterator;
import java.util.List;

public class ScheduleAjax {

    @Autowired
    private Scheduler scheduler;

    public ScheduleStartResponse start(ScheduleStartRequest request) {
        ScheduleStartResponse response = new ScheduleStartResponse();
        if (!scheduler.start(request.getId())) {
            response.addError(ErrorType.BUSINESS_ERROR, "启动失败!");
        }
        return response;
    }

    public ScheduleStopResponse stop(ScheduleStopRequest request) {
        ScheduleStopResponse response = new ScheduleStopResponse();
        if (!scheduler.stop(request.getId())) {
            response.addError(ErrorType.BUSINESS_ERROR, "停止失败!");
        }
        return response;
    }

    public ScheduleFindResponse find(ScheduleFindRequest request) {
        ScheduleFindResponse response = new ScheduleFindResponse();
        List<Scheduler.Schedule> schedules = scheduler.taskList();
        Iterator<Scheduler.Schedule> iterator = schedules.iterator();
        while (iterator.hasNext()) {
            Scheduler.Schedule next = iterator.next();
            if (!StringUtil.isEmpty(request.getTaskId()) && !next.getId().contains(request.getTaskId())) {
                iterator.remove();
            }
            if (!StringUtil.isEmpty(request.getTaskName()) && !next.getName().contains(request.getTaskName())) {
                iterator.remove();
            }
            if (request.getRun() != null && next.isRun() != request.getRun()) {
                iterator.remove();
            }
        }
        response.setResult(schedules);
        return response;
    }
}
